<template>
  <!--
  查：
    1：定义新增api
    2:导入
    3：进入页面调用
    4：存储数据并渲染
    5：和分页建立关联处理
  增
    1：创建一个新增弹框组件
    2：在父组件使用
    3：点击新增打开弹框
    4：完成内部布局
    5：完成表单验证
    6：定义新增api
    7:点击确定时调用
    8：调用成功
       a:提示
       b:清空表单数据与验证
       c:关闭弹框
       d:刷新父级列表数据
   删除
     1：点击绑定弹出确定框
     2：定义删除api
     3：导入删除api
     4:确定框点击确定后调用api
     5:调用成功
       提示
       刷新列表数据
          当前页码>1 该页只有一条数据
          页码-1再刷新
 -->
  <!-- qrcode
            1:下载安装  yarn add qrcode
            2:导入  import Qrcode from 'qrcode'
            3:创建一个canvas标签
              <canvas ref="canvas" />
            4:Qrcode.toCanvas(this.$refs.canvas,"需要转换的内容(http://www.baidu.com)",{
            二维码的配制：宽/高
            width:500,
            height:500
            })

   打印插件
         vue-print-nb
      1:下载安装  yarn add vue-print-nb
      2:导入注册使用
          main.js
             import Print from 'vue-print-nb'
             Vue.use(Print)
             重点提供了一个自定义指令,用于打印的按钮 v-print="{id:需要打印的dom的id}"
      3：将需要打印dom区域用id="xxx"
      4:打印按钮  v-print="{id:‘xxx’}"

   弹框
      ref
      v-model
      .sync
      1:创建弹框组件
      2：使用弹框组件
      3：传值value的值
      4：弹框组件接收使用
      5：弹框组件上绑定input方法
      6：弹框组件内使用this.$emit('input',false)来关闭弹框

  -->
  <div class="employees">
    <el-card>
      <div class="top">
        <el-tag> <i class="el-icon-info" /> 共{{ page.total }}条记录</el-tag>
        <div class="right">
          <el-button
            type="danger"
            size="small"
            @click="output"
          >普通excel导出</el-button>
          <el-button type="info" size="small">复杂表头excel导出</el-button>
          <el-button
            type="success"
            size="small"
            @click="$router.push('/employees/import')"
          >excel导入</el-button>
          <el-button
            type="primary"
            size="small"
            @click="addClick"
          >新建员工</el-button>
        </div>
      </div>
    </el-card>
    <el-card>
      <el-table :data="list" border>
        <el-table-column label="序号">
          <template v-slot="{ $index }">
            {{ (page.page - 1) * page.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column prop="staffPhoto" label="头像">
          <template v-slot="{ row }">
            <img
              v-errorImg
              class="avatar"
              :src="row.staffPhoto"
              alt=""
              @click="imgClick(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable />
        <el-table-column prop="workNumber" label="工号" />
        <el-table-column prop="formOfEmployment" label="聘用形式" sortable>
          <template v-slot="{ row }">
            <div v-formatter:hireType="row.formOfEmployment" />
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template v-slot="{ row }">
            <div>
              {{ row.timeOfEntry | formatTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="状态">
          <template v-slot="{ row }">
            <div v-formatter:stausInfos="row.enableState" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template v-slot="{ row }">
            <el-button
              type="text"
              @click="$router.push('/employees/detail/' + row.id)"
            >查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleClick(row)">角色</el-button>
            <!--
              1：常规使用 v-if="判断"
              2：工具型方法   v-if="hasPermissionBtn('employees_index_delbutton')"
              3:全局混入用法
                 mixin
              4:自定义指令
             -->
            <!-- <el-button
              v-buttonShow="'employees_index_delbutton'"
              type="text"
              @click="del(row.id)"
            >删除</el-button> -->
            <el-button
              v-if="isShowBtn('employees_index_delbutton')"
              type="text"
              @click="del(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1, 5, 10, 20, 100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <!-- <Add :is-show="show" @update:isShow="show = $event" /> -->
    <Add :is-show.sync="show" @getData="getData" />
    <!-- 二维码弹框
    el-dialog它内部的默认插槽内容是在第一次打开dialog弹框后才渲染的
    -->
    <el-dialog title="图片二维码" :visible.sync="showCode">
      <div style="text-align: center">
        <canvas ref="canvas" />
      </div>
    </el-dialog>
    <!-- 角色弹框组件 -->
    <!-- <Role :value="roleShow" @input="roleShow = $event" /> -->
    <Role ref="role" v-model="roleShow" />
  </div>
</template>
<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import jsCookie from 'js-cookie'
import employees from '@/api/constant/employees'
import Add from './components/add'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import moment from 'moment'
import Qrcode from 'qrcode'
import Role from './components/role'
import { hasPermissionBtn } from '@/utils'
import mixinjs from '@/mixins'
export default {
  components: {
    Add,
    Role
  },
  mixins: [mixinjs],
  data() {
    return {
      hasPermissionBtn,
      roleShow: false,
      showCode: false,
      show: false,
      list: [],
      page: {
        page: 1, //	是	1	页码
        // 读取页容量值
        size: +jsCookie.get('employees-size') || 1, //	是	10	每页条数
        total: 100
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 页容量
    handleSizeChange(size) {
      // this.page.size = size
      // console.log(size, this.page.size)
      // 存储页容量值到cookie
      jsCookie.set('employees-size', size)
      this.getData()
    },
    // 页码改变
    handleCurrentChange() {
      // this.page.page = page
      // console.log(page, this.page.page)
      this.getData()
    },
    async getData() {
      const res = await sysUser(this.page)
      this.list = res.data.data.rows
      this.page.total = res.data.data.total
      // console.log('员工列表', res)
    },
    // 聘用形式数据转换
    formatter(row, column, cellValue, index) {
      //  employees.hireType  [{id:1,value:正式}]
      //  cellValue  1
      // 返回值=数组.find(item=>{return boolean})  boolean:true 返回值=当前项的item  找不到返回值=undefined
      const findItem = employees.hireType.find((item) => item.id === cellValue)
      return findItem ? findItem.value : '-'
    },
    // 新增事件
    addClick() {
      this.show = true
    },
    // 删除事件
    del(id) {
      this.$confirm('您确定删除该项吗？', '提示')
        .then(async() => {
          await sysUserDelete(id)
          this.$message.success('删除成功')
          if (this.page.page > 1 && this.list.length === 1) {
            this.page.page--
          }
          this.getData()
        })
        .catch(() => {})
    },
    // 导出事件
    async output() {
      // 拿到所有的员工数据
      const res = await sysUser({ page: 1, size: 99999 })
      const userList = res.data.data.rows
      // 写出规则

      const rules = {
        姓名: 'username',
        头像: 'staffPhoto',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry',
        状态: 'enableState'
      }

      const listArr = userList.map((item) => {
        const newArr = []
        Object.values(rules).forEach((key) => {
          if (key === 'timeOfEntry') {
            newArr.push(moment(item[key]).format('YYYY-MM-DD'))
          } else {
            newArr.push(item[key])
          }
        })
        return newArr
      })

      // console.log(userList)

      export_json_to_excel({
        header: Object.keys(rules),
        data: listArr,
        filename: '员工数据'
      })
    },
    // 头像点击
    imgClick(imgSrc) {
      if (!imgSrc) {
        this.$message.warning('没有头像地址！')
        return
      }
      this.showCode = true
      // 等到第一次打开弹框canvas渲染完成后生成二维码
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.canvas, imgSrc, {
          width: 300,
          height: 300
        })
      })
    },
    // 角色点击
    roleClick(row) {
      this.roleShow = true
      console.log('row', row)
      this.$refs.role.getUserInfo(row.id)
    }
  }
}
</script>
<style lang="scss" scoped>
.employees {
  padding: 20px;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .right {
    display: flex;
  }
  .page {
    padding: 15px 0;
    text-align: right;
  }
  .avatar {
    width: 30px;
    height: 30px;
    object-fit: cover;
  }
}
</style>
